package com.example.big_event.controller;

import com.example.big_event.Utils.Result;
import com.example.big_event.Utils.ThreadLocalUtil;
import com.example.big_event.pojo.entity.Article;
import com.example.big_event.service.ArticleService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    /**
     * 新增文章
     *
     * @param article 需要新增的文章
     * @return 成功或者失败的结果
     */
    @PostMapping("/add")
    public Result<Article> addArticle(@RequestBody Article article) {
        // 从线程中获取用户ID
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer createId = (Integer) map.get("id");
        // 将用户ID同步到文章中
        article.setCreateUser(createId);
        boolean isSuccess = articleService.save(article);
        return isSuccess ? Result.success() : Result.error("添加失败");
    }

    /**
     * 文章的分页查询
     * @param pageNum 从第几页开始查询
     * @param pageSize 一页有多少条数据
     * @return 分页对象
     */
    @GetMapping("/page")
    public Result<PageInfo<Article>> pageQuery(int pageNum,int pageSize){
        PageInfo<Article> pageInfo = articleService.pageQuery(pageNum,pageSize);
            return Result.success(pageInfo);
    }
}
